package com.stylefeng.guns.biz.api.controller;

import com.stylefeng.guns.biz.api.cloopen.SendTemplateSMS;
import com.stylefeng.guns.core.redis.RedisService;
import com.stylefeng.guns.core.result.BaseResultVo;
import com.stylefeng.guns.core.result.JsonReturnHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 短信接口
 */
@Controller
@RequestMapping("/api/pc/unauthorized")
public class MessageController {

    @Autowired
    private RedisService redisService;

    /**
     * 发送验证码
     *
     * @return
     */
    @RequestMapping("/sendMessage")
	@ResponseBody
    public BaseResultVo sendMessage(String mobile) {

        Map<String, String> retMap = new HashMap<>();
    
        //如果redis不存在该手机号码对应的验证码或者存在时长超过2分钟，允许重新发送短信
        if (StringUtils.isEmpty(redisService.getValue(mobile)) || redisService.getExpire(mobile) < 60 * 29){
            //发送短信
        	String code = getSix();
        	SendTemplateSMS.sendMsg(mobile,"319791",new String [] {code,"5"});
            //验证码有效时间5分钟
            redisService.addKeyValue(mobile,code ,5*60);
//            redisService.addKeyValue(mobile,"123456",5*60);
            retMap.put("retCode","000000");
            retMap.put("retMsg", "短信发送成功");
        } else {
            retMap.put("retCode","000001");
            retMap.put("retMsg", "2分钟内只允许发送一条短信");
        }

        return JsonReturnHelper.getSuccessWithData(retMap);

    }


    /**
     * 产生随机的六位数
     *
     * @return
     */
    public static String getSix() {
        Random rad = new Random();
        String result = rad.nextInt(1000000) + "";

        if (result.length() != 6) {
            return getSix();
        }
        return result;
    }

}